/**
 * 直播间管理页面
 * 用于管理直播间的创建、删除、刷新状态等操作
*/
import React, { useState, useEffect, useRef } from 'react';
import { Table, Button, Modal, Form, Input, Space, Popconfirm, message, Tag, Typography } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, SyncOutlined, VideoCameraOutlined, MessageOutlined, StopOutlined, UploadOutlined, DownloadOutlined, LinkOutlined } from '@ant-design/icons';

const { Link } = Typography;
import { Room, RoomsResponse } from '../types/Room';
import { useRooms } from '../hooks/useRooms';
import { API_ENDPOINTS, PAGINATION_CONFIG, MESSAGES } from '../constants/api';
import { parseRoomImportText, readTextFile } from '../utils/roomImport';
import { triggerRoomsExportDownload } from '../utils/roomExport';
import { api, ApiError } from '../utils/api';

const RoomsPage: React.FC = () => {
  const { rooms, loading, fetchRooms, pagination, updateLiveStatus, updateSingleRoomStatus, createRoom, updateRoom, deleteRoom } = useRooms();
  const [refreshingAll, setRefreshingAll] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRoom, setEditingRoom] = useState<Room | null>(null);
  const [importing, setImporting] = useState(false);
  const [exporting, setExporting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const [form] = Form.useForm();

  // 创建或更新房间
  const handleSubmit = async (values: any) => {
    const success = editingRoom 
      ? await updateRoom(editingRoom.id, values)
      : await createRoom(values);
    
    if (success) {
      setModalVisible(false);
      setEditingRoom(null);
      form.resetFields();
    }
  };

  // 删除房间
  const handleDelete = async (id: string) => {
    await deleteRoom(id);
  };

  // 打开编辑模态框
  const handleEdit = (room: Room) => {
    setEditingRoom(room);
    form.setFieldsValue({
      id: room.id,
      type: room.type,
      weight: room.weight,
    });
    setModalVisible(true);
  };

  // 打开新建模态框
  const handleAdd = () => {
    setEditingRoom(null);
    form.resetFields();
    setModalVisible(true);
  };



  // 刷新所有直播状态
  const handleRefreshStatus = async () => {
    setRefreshingAll(true);
    await updateLiveStatus(rooms);
    setRefreshingAll(false);
    message.success('直播状态已刷新');
  };

  // 刷新单个房间状态
  const handleRefreshSingleStatus = async (roomId: string) => {
    await updateSingleRoomStatus(roomId);
  };

  // 获取直播状态显示
  const getLiveStatusTag = (status?: number, refreshing?: boolean) => {
    if (refreshing) {
      return (
        <Tag icon={<SyncOutlined spin />} color="processing">
          刷新中
        </Tag>
      );
    }
    
    switch (status) {
      case 2:
        return <Tag color="green">直播中</Tag>;
      case 4:
        return <Tag color="default">未开始</Tag>;
      case 0:
        return <Tag color="orange">已结束</Tag>;
      case undefined:
      default:
        return <Tag color="default">未知</Tag>;
    }
  };



  useEffect(() => {   
    async function run(){
      await fetchRooms();
    } 
    run();
  }, []);
  
  const handleTableChange = async (page: number, pageSize?: number) => {
    const nextPageSize = pageSize ?? pagination.pageSize;
    await fetchRooms(page, nextPageSize);
  };

  const fetchAllRoomsForExport = async (): Promise<Room[]> => {
    const collected: Room[] = [];
    const pageSize = 200;
    let page = 1;
    let total = Infinity;

    while (collected.length < total) {
      const query = new URLSearchParams({ page: String(page), limit: String(pageSize) }).toString();
      const response = await api.get<RoomsResponse>(`${API_ENDPOINTS.ROOMS}?${query}`);

      if (!response.success || !response.data) {
        throw new Error('获取房间列表失败');
      }

      const pageRooms = response.data.rooms || [];
      collected.push(...pageRooms);

      const pageInfo = response.data.pagination;
      if (pageInfo) {
        total = pageInfo.total;
        if (page >= pageInfo.totalPages) {
          break;
        }
      }

      if (pageRooms.length < pageSize) {
        break;
      }

      page += 1;
      if (page > 1000) {
        break;
      }
    }

    return collected;
  };

  const handleExportRooms = async () => {
    if (exporting) {
      return;
    }

    setExporting(true);
    try {
      const allRooms = await fetchAllRoomsForExport();
      if (!allRooms || allRooms.length === 0) {
        message.info('暂无房间可导出');
        return;
      }

      triggerRoomsExportDownload(allRooms);
      message.success(`已导出 ${allRooms.length} 个房间`);
    } catch (error) {
      const text = error instanceof ApiError ? `${error.message}` : (error instanceof Error ? error.message : '导出失败');
      message.error(text || '导出失败');
    } finally {
      setExporting(false);
    }
  };

  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const showImportSummary = (successIds: string[], failureDetails: Array<{ label: string; message: string }>) => {
    Modal.info({
      title: '导入结果',
      width: 540,
      content: (
        <div>
          <p>成功 {successIds.length} 条，失败 {failureDetails.length} 条。</p>
          {successIds.length > 0 && (
            <div style={{ marginBottom: 12 }}>
              <strong>成功：</strong>
              <div style={{ maxHeight: 160, overflow: 'auto', marginTop: 6 }}>
                {successIds.map(id => (
                  <div key={`success-${id}`}>{id}</div>
                ))}
              </div>
            </div>
          )}
          {failureDetails.length > 0 && (
            <div>
              <strong>失败详情：</strong>
              <div style={{ maxHeight: 200, overflow: 'auto', marginTop: 6 }}>
                {failureDetails.map((item, index) => (
                  <div key={`failure-${index}`}>
                    {item.label}: {item.message}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      ),
    });
  };

  const handleImportFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (event.target) {
      event.target.value = '';
    }
    if (!file) {
      return;
    }

    setImporting(true);
    try {
      const text = await readTextFile(file);
      const { entries, errors } = parseRoomImportText(text);

      const successIds: string[] = [];
      const failureDetails: Array<{ label: string; message: string }> = errors.map(error => ({
        label: `第 ${error.lineNumber} 行`,
        message: error.message,
      }));

      if (entries.length === 0) {
        message.error('导入文件没有有效的房间号');
        showImportSummary(successIds, failureDetails);
        return;
      }

      for (const entry of entries) {
        try {
          await api.post<Room>(API_ENDPOINTS.ROOMS, { id: entry.roomId });
          successIds.push(entry.roomId);
        } catch (error) {
          let reason = '导入失败';
          if (error instanceof ApiError) {
            reason = `HTTP ${error.status}: ${error.message}`;
          } else if (error instanceof Error) {
            reason = error.message;
          }
          failureDetails.push({
            label: `第 ${entry.lineNumber} 行`,
            message: `${entry.roomId}: ${reason}`,
          });
        }
      }

      showImportSummary(successIds, failureDetails);

      if (failureDetails.length === 0 && successIds.length > 0) {
        message.success(`成功导入 ${successIds.length} 个房间`);
      } else if (failureDetails.length > 0) {
        message.warning('导入完成，部分条目失败');
      }

      if (successIds.length > 0) {
        await fetchRooms(1, pagination.pageSize);
      }
    } catch (error) {
      const messageText = error instanceof Error ? error.message : '导入失败';
      message.error(messageText);
    } finally {
      setImporting(false);
    }
  };


  // 开始录制直播间
  const handleStartRecord = async (roomId: string) => {
    try {
      const response = await fetch('/api/recording/start', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          roomId,
          quality: 'high'
        }),
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          // 同时连接弹幕
          const danmuResp = await fetch('/api/dycast/connectLiveRoom', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ roomId }),
          });
          if (danmuResp.ok) {
            message.success(`直播间 ${roomId} 开始录制并连接弹幕`);
          } else {
            message.warning(`直播间 ${roomId} 开始录制，但弹幕连接失败`);
          }
          // 刷新房间数据以更新录制状态
          await fetchRooms();
        } else {
          message.error(result.message || '开始录制失败');
        }
      } else {
        const errorResult = await response.json();
        message.error(errorResult.message || '开始录制失败');
      }
    } catch (error) {
      console.error('录制直播间错误:', error);
      message.error('开始录制失败');
    }
  };

  // 停止录制直播间
  const handleStopRecord = async (roomId: string) => {
    try {
      const response = await fetch('/api/recording/stop', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ roomId }),
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.success) {
          message.success(`直播间 ${roomId} 停止录制`);
          // 刷新房间数据以更新录制状态
          await fetchRooms();
        } else {
          message.error(result.message || '停止录制失败');
        }
      } else {
        const errorResult = await response.json();
        message.error(errorResult.message || '停止录制失败');
      }
    } catch (error) {
      console.error('停止录制错误:', error);
      message.error('停止录制失败');
    }
  };

  // 弹幕/连接直播间
  const handleDanmu = async (roomId: string) => {
    try {
      const response = await fetch('/api/dycast/connectLiveRoom', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ roomId }),
      });
      
      if (response.ok) {
        message.success(`直播间 ${roomId} 弹幕连接成功`);
      } else {
        message.error('连接弹幕失败');
      }
    } catch (error) {
      console.error('连接弹幕错误:', error);
      message.error('连接弹幕失败');
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 200,
    },
    {
      title: '房间标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string | null) => text || '-',
    },
    {
      title: '直播间链接',
      key: 'liveRoomUrl',
      render: (record: Room) => {
        const liveUrl = `https://live.douyin.com/${record.id}`;
        return (
          <Link
            href={liveUrl}
            target="_blank"
            rel="noopener noreferrer"
            style={{ display: 'flex', alignItems: 'center', gap: '4px' }}
          >
            <LinkOutlined />
            {record.streamerName || record.id}
          </Link>
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: string | null) => text || '-',
    },
    {
      title: '权重',
      dataIndex: 'weight',
      key: 'weight',
      render: (value: number | null) => value !== null ? value : '-',
    },
    {
      title: '直播状态',
      key: 'liveStatus',
      render: (record: Room) => (
        <Space>
          {getLiveStatusTag(record.liveStatus, record.refreshing)}
          <Button
            type="text"
            size="small"
            icon={<ReloadOutlined />}
            loading={record.refreshing ?? false}
            onClick={() => handleRefreshSingleStatus(record.id)}
            title="刷新状态"
          />
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (record: Room) => (
        <Space>
          {/* 视频录制按钮 */}
          {record.isVideoRecording ? (
            <Button
              type="primary"
              size="small"
              icon={<StopOutlined />}
              onClick={() => handleStopRecord(record.id)}
              title="停止录制"
              danger
              style={{ backgroundColor: '#ff4d4f', borderColor: '#ff4d4f' }}
            />
          ) : (
            <Button
              type="default"
              size="small"
              icon={<VideoCameraOutlined />}
              onClick={() => handleStartRecord(record.id)}
              title="开始录制（包含视频和弹幕）"
            />
          )}
          {/* 弹幕按钮 */}
          {record.isDanmuRecording ? (
            <Button
              type="default"
              size="small"
              icon={<MessageOutlined />}
              title="弹幕采集中"
              style={{ backgroundColor: '#1890ff', borderColor: '#1890ff', color: '#fff' }}
            />
          ) : (
            <Button
              type="default"
              size="small"
              icon={<MessageOutlined />}
              onClick={() => handleDanmu(record.id)}
              title="连接弹幕（仅弹幕，不录制视频）"
            />
          )}
          <Button
            type="default"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            title="编辑"
          />
          <Popconfirm
            title={MESSAGES.CONFIRM.DELETE}
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              size="small"
              icon={<DeleteOutlined />}
              title="删除"
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <input
        type="file"
        accept=".txt,text/plain"
        ref={fileInputRef}
        style={{ display: 'none' }}
        onChange={handleImportFileChange}
      />
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <Button
            icon={<UploadOutlined />}
            loading={importing}
            onClick={handleImportClick}
          >
            导入房间
          </Button>
          <Button
            icon={<DownloadOutlined />}
            onClick={handleExportRooms}
            loading={exporting}
          >
            导出房间
          </Button>
        </Space>
        <Space>
          <Button
            icon={<ReloadOutlined />}
            onClick={handleRefreshStatus}
            loading={refreshingAll}
          >
            刷新直播状态
          </Button>
          {/* 移除“刷新录制状态”按钮，录制/弹幕状态随 /api/rooms 返回 */}
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新建房间
          </Button>
        </Space>
      </div>
      
      <Table
        columns={columns}
        dataSource={rooms}
        rowKey="id"
        loading={loading}
        pagination={{
          current: pagination.page,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: PAGINATION_CONFIG.SHOW_SIZE_CHANGER,
          showQuickJumper: PAGINATION_CONFIG.SHOW_QUICK_JUMPER,
          showTotal: PAGINATION_CONFIG.SHOW_TOTAL,
          onChange: handleTableChange,
        }}
      />

      <Modal
        title={editingRoom ? '编辑房间' : '新建房间'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingRoom(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        okText="确定"
        cancelText="取消"
      >
        <Form
           form={form}
           layout="vertical"
           onFinish={handleSubmit}
         >
           <Form.Item
             label="房间ID"
             name="id"
             rules={[{ required: true, message: '请输入房间ID' }]}
           >
             <Input placeholder="请输入房间ID" />
           </Form.Item>
           <Form.Item
             label="类型"
             name="type"
           >
             <Input placeholder="请输入房间类型" />
           </Form.Item>
           <Form.Item
             label="权重"
             name="weight"
           >
             <Input type="number" placeholder="请输入权重值" />
           </Form.Item>
         </Form>
      </Modal>
    </div>
  );
};

export default RoomsPage;
